package saucaca.fragment;

import java.util.ArrayList;

import lemon.kenhnhacvn.BaseActivity;
import lemon.kenhnhacvn.BaseEngine;
import lemon.kenhnhacvn.MainActivity;
import lemon.kenhnhacvn.R;

import org.json.JSONException;

import saucaca.CustomView.CircularImageView;
import saucaca.Download.DownloadTask;
import saucaca.JSON.JsonReader;
import saucaca.JSON.WServiceLib;
import saucaca.Object.RingtoneObject;
import saucaca.Object.SongObject;
import saucaca.Util.CMD;
import saucaca.Util.TagName;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainListteningContent extends Fragment {
	SongObject songObject;
	Context context;
//	TextView txtLyric;
	ImageView imgDownload, imgShare, imgClip, imgRingtone;
	CircularImageView imgAlbum;
	WebView webView;
	public MainListteningContent(Context context, SongObject songObject) {
		this.songObject = songObject;
		this.context = context;
	}

	public void update(SongObject songObject) {
		this.songObject = songObject;
		if (this.songObject != null)
			showInfo();
		hideShowMenu(songObject.getFormNet());
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.listening_content_main, container, false);
		findviewbyid(view);
		if (songObject != null)
			showInfo();
		hideShowMenu(songObject.getFormNet());
			
		return view;
	}

	public void findviewbyid(View view) {
//		txtLyric = (TextView) view.findViewById(R.id.listening_lyric);
		imgAlbum = (CircularImageView) view.findViewById(R.id.listening_album_picture);
		Animation AlbumAnimation = AnimationUtils.loadAnimation(context, R.anim.rotate2);
		AlbumAnimation.setRepeatCount(Animation.INFINITE);
		imgAlbum.setAnimation(AlbumAnimation);
		imgDownload = (ImageView) view.findViewById(R.id.main_download);
		imgShare = (ImageView) view.findViewById(R.id.main_share);
		imgClip = (ImageView) view.findViewById(R.id.main_video);
		imgRingtone = (ImageView) view.findViewById(R.id.main_ringtone);
		webView =(WebView) view.findViewById(R.id.listening_lyric_webView);
//		webView.setBackgroundColor(Color.TRANSPARENT);
		imgDownload.setOnClickListener(clickListener);
		imgShare.setOnClickListener(clickListener);
		imgClip.setOnClickListener(clickListener);
		imgRingtone.setOnClickListener(clickListener);
	}

	OnClickListener clickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.main_download:
				if (songObject.getFormNet()) {
					DownloadTask downloadTask = new DownloadTask(context, songObject);
					downloadTask.startDownload();
				} else
					TagName.showToastShort(context, "Bài hát đã có sẵn trong thiết bị!");
				break;
			case R.id.main_share:
				BaseEngine.shareTextUrl(context, songObject.getTXNAME(), songObject.getTXURL());
				break;
			// case R.id.main_video:
			// break;
			case R.id.main_ringtone:
				if(!songObject.getFormNet())
					if(!BaseEngine.convertStringLongtoInteger(songObject.getISTONE()).equals("0")){
						RingtoneObject ringtoneObject=new RingtoneObject();
						ringtoneObject.setSONG_ID(songObject.getSONG_ID());
						ringtoneObject.setTXNAME(songObject.getTXNAME());
						((MainActivity) context).switchContent(RingToneListSong.class.getName(), ringtoneObject);
					}else Toast.makeText(context, "Đang cập nhật", Toast.LENGTH_SHORT).show();
//				if (!songObject.getFormNet()) {
//					new AlertDialog.Builder(context).setTitle("Cài nhạc chuông!").setMessage("Bạn muốn cài bài hát:' " + songObject.getTXNAME() + "'" + " làm nhạc chuông?")
//							.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
//								public void onClick(DialogInterface dialog, int which) {
//
//									// File k = new
//									// File(songObject.getPATCH_FULL(), null);
//									ContentValues values = new ContentValues();
//									values.put(MediaStore.MediaColumns.DATA, songObject.getPATCH_FULL());
//									values.put(MediaStore.MediaColumns.TITLE, songObject.getTXNAME());
//									values.put(MediaStore.MediaColumns.SIZE, songObject.getSize());
//									values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/*");
//									values.put(MediaStore.Audio.Media.ARTIST, songObject.getNAME_SINGERS());
//									values.put(MediaStore.Audio.Media.DURATION, songObject.getduration());
//									values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
//									values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);
//									values.put(MediaStore.Audio.Media.IS_ALARM, false);
//									values.put(MediaStore.Audio.Media.IS_MUSIC, false);
//									// Insert it into the database
//									Uri uri = MediaStore.Audio.Media.getContentUriForPath(songObject.getPATCH_FULL());
//									Uri newUri = context.getContentResolver().insert(uri, values);
//									RingtoneManager.setActualDefaultRingtoneUri(context, RingtoneManager.TYPE_RINGTONE, newUri);
//								}
//							}).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
//								public void onClick(DialogInterface dialog, int which) {
//								}
//							}).setIcon(android.R.drawable.ic_dialog_alert).show();
//
//				} else
//					TagName.showToastShort(context, "Tải bài hát về thiết bị trước khi cài nhạc chuông!");
				break;

			default:
				TagName.showToastShort(context, "Đang cập nhật!");
				break;
			}
		}
	};

	void hideShowMenu(boolean isOnline) {
		if (isOnline) {
			imgDownload.setVisibility(View.VISIBLE);
			imgShare.setVisibility(View.VISIBLE);
			imgClip.setVisibility(View.VISIBLE);
			imgRingtone.setVisibility(View.VISIBLE);
		} else {
			imgDownload.setVisibility(View.GONE);
			imgShare.setVisibility(View.GONE);
			imgClip.setVisibility(View.GONE);
			imgRingtone.setVisibility(View.GONE);
		}
	}

	void showInfo() {
		if (songObject != null) {
			if(songObject.getLYRCIS()!=null){
				final String mimeType = "text/html";
				final String encoding = "utf-8";
				String data =Html.fromHtml(songObject.getLYRCIS()).toString();
				webView.loadDataWithBaseURL(null,data, mimeType, encoding,null);
			}
//			txtLyric.setText(songObject.getLYRCIS());
			if (songObject.getFormNet()) {
				BaseActivity.imageLoader.displayImage(songObject.getAVATAR(), imgAlbum, BaseActivity.options);
				new songDetailsServices().execute("");
			} else {
				Bitmap bm = BitmapFactory.decodeFile(songObject.getAVATAR());
				if (bm != null) {
					BitmapDrawable bmpDraw = new BitmapDrawable(bm);
					imgAlbum.setImageDrawable(bmpDraw);
				}
			}
		}
	}

	class songDetailsServices extends AsyncTask<String, String, String> {
		@Override
		protected String doInBackground(String... params) {
			String str = WServiceLib.idDetais(CMD.CMD_SONG_DETAIL, songObject.getSONG_ID());
			return str;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			if (result != null)
				try {
					ArrayList<SongObject> listsongs = JsonReader.readSongdetail(result);
					if (listsongs != null && listsongs.size() > 0){
						if(listsongs.get(0).getLYRCIS()!=null){
							final String mimeType = "text/html";
							final String encoding = "utf-8";
							String data =Html.fromHtml(listsongs.get(0).getLYRCIS()).toString();
							webView.loadDataWithBaseURL(null,data, mimeType, encoding,null);
						}
	//						txtLyric.setText(listsongs.get(0).getLYRCIS());
						// BaseActivity.imageLoader.displayImage(songObject.getAVATAR(),
						// imgAlbum, BaseActivity.options);
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
		}
	}
}
